package com.example.takeaway.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.takeaway.common.R;
import com.example.takeaway.entity.Category;
import com.example.takeaway.entity.Dish;
import com.example.takeaway.entity.DishDto;
import com.example.takeaway.entity.DishFlavor;
import com.example.takeaway.service.CategoryService;
import com.example.takeaway.service.DishFlavorService;
import com.example.takeaway.service.DishService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
@AllArgsConstructor
public class DishController {

    private final DishService dishService;
    private final CategoryService categoryService;
    private final DishFlavorService dishFlavorService;
    private final RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */


    @PostMapping
    public R<String> AddDish(@RequestBody DishDto dishDto){


        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");


    }

    /**
     * 菜品信息分页
     * @param page
     * @param pageSize
     * @return
     */

    @GetMapping("/page")
    public R<Page> page(int page , int pageSize , String name){

        //分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        // 构造查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>()
                .like(name != null, Dish::getName, name)
                .orderByAsc(Dish::getSort);

        //执行分页查询
        dishService.page(dishPage, wrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);



            Long categoryId = item.getCategoryId(); //分类id

            //根据分类id查询分类对象
            if(categoryService.getById(categoryId) != null){
                Category category = categoryService.getById(categoryId);
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);

                return dishDto;
            }


            return null;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(list);


        return R.success(dishDtoPage);


    }

    /**
     * 修改菜品  --- 数据回显
     */

    @GetMapping("/{ids}")
    public R<DishDto> UpdateShow(@PathVariable Long ids){

        DishDto dishDto = dishService.GetByIdWithFlavor(ids);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success(dishDto);


    }

    /**
     * 更新菜品
     */

    @PutMapping
    public R<String> PutData(@RequestBody DishDto dishDto){
        log.info("更新数据");


        dishService.updateWithFlavor(dishDto);


        //清除菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);


        return R.success("新增菜品成功");

    }

    /**
     * 删除菜品
     */

    @DeleteMapping
    public R<String> DeleteById(@RequestParam("ids") List<Long> ids){

        log.info("id值为：{}",ids.toString());


        List<Dish> dishList = dishService.listByIds(ids);
        for (Dish dish : dishList) {
            //清理某个分类下面的菜品缓存数据
            String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

            if(redisTemplate.opsForValue().get(key) != null){
                redisTemplate.delete(key);
            }


        }

        dishService.DeleteByIds(ids);





        return R.success("成功删除");


    }

//    /**
//     * 根据条件查询菜品数据
//     * @param categoryId
//     * @return
//     */
//
//
//    @GetMapping("/list")
//    public R<List<Dish>> listName(Long categoryId){
//
//
//        log.info("查询的id是:{}",categoryId);
//
//        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        dishLambdaQueryWrapper.eq(Dish::getCategoryId,categoryId);
//        dishLambdaQueryWrapper.orderByAsc(Dish::getSort);
//        dishLambdaQueryWrapper.orderByAsc(Dish::getUpdateTime);
//        dishLambdaQueryWrapper.eq(Dish::getStatus , 1);
//
//
//
//        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
//
//        return R.success(list);
//
//
//    }

    @GetMapping("/list")
    public R<List<DishDto>> listName2(Dish dish){

        List<DishDto> collect = null;

        Long categoryId = dish.getCategoryId();

        log.info("查询的id是:{}",categoryId);

        String key = "dish_" + categoryId + "_" + dish.getStatus();

        //先从redis中查询数据
        collect  = (List<DishDto>)redisTemplate.opsForValue().get(key);

        if(collect != null){
            //如果存在 直接返回 无需查询数据库
            return R.success(collect);
        }



        //如果不存在  我们需要查询数据库


        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,categoryId);
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort);
        dishLambdaQueryWrapper.orderByAsc(Dish::getUpdateTime);
        dishLambdaQueryWrapper.eq(Dish::getStatus , 1);



        List<Dish> list = dishService.list(dishLambdaQueryWrapper);


        collect = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId1 = item.getCategoryId();
            Category byId = categoryService.getById(categoryId1);

            if(byId != null){
                String name = byId.getName();
                dishDto.setCategoryName(name);
            }

            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list1);


            return dishDto;
        }).collect(Collectors.toList());


        //将查询的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key ,collect , 60 , TimeUnit.MINUTES);


        return R.success(collect);


    }


}
